<template>
  <div>
    <el-input v-model="model" v-if="type === 'input'" v-bind="$attrs" />
    <el-select
      v-model="model"
      v-if="type === 'select'"
      v-bind="$attrs"
      placeholder="请选择"
    >
      <el-option
        v-for="item in listData"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
    <el-input
      v-model="model"
      v-if="type === 'function'"
      type="textarea"
      rows="4"
      v-bind="$attrs"
    />
    <el-input
      v-model="model"
      v-if="type === 'textarea'"
      type="textarea"
      v-bind="$attrs"
    />
    <div
      v-if="type === 'array'"
      style="display: flex; flex-wrap: wrap; gap: 10px"
    >
      <el-tag
        v-for="(tag, index) in model"
        :key="tag.value"
        closable
        @close="removeArrayTag(index)"
      >
        {{ tag.label }}
      </el-tag>
      <el-tag type="info" @click="arrayAddShow = true">+ 添加</el-tag>
    </div>
    <el-dialog v-model="arrayAddShow" title="添加" width="500" append-to-body>
      <el-form
        :model="arrayAddForm"
        label-width="auto"
        style="max-width: 600px"
      >
        <el-form-item label="label">
          <el-input v-model="arrayAddForm.label" />
        </el-form-item>
        <el-form-item label="value">
          <el-input v-model="arrayAddForm.value" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleArrayAdd">添加</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
const model = defineModel();
const props = defineProps({
  type: {
    type: String,
    default: "input",
  },
  listData: {
    type: Array,
    default: () => [],
  },
  defaultValue: {
    type: [String, Number, Array],
    default: undefined,
  },
});
const arrayAddShow = ref(false);
const arrayAddForm = ref({
  label: "",
  value: "",
});
const handleArrayAdd = () => {
  model.value.push(JSON.parse(JSON.stringify(arrayAddForm.value)));
};
const removeArrayTag = (index) => {
  model.value.splice(index, 1);
};

// Watch model for type === 'function' to wrap it with backticks
watch(
  () => model.value,
  (newValue, oldValue) => {
    if (props.type === "function") {
      // Check if the model is already wrapped with backticks, if not, wrap it
      if (!newValue.startsWith("```") || !newValue.endsWith("```")) {
        model.value = `\`\`\`\n${newValue}\n\`\`\``;
      }
    }
  }
);

onMounted(() => {
  if (props.defaultValue && !model.value) {
    model.value = props.defaultValue;
  }
  if (props.type === "array") {
    model.value = model.value || [];
  }
});
</script>

<style lang="scss" scoped></style>
